#include "Tile.h"

Tile::Tile(TextureManager * textureManager)
{
	this->textureManager = textureManager;
	fileName = NULL;
	textureIndex = -1;
}
Tile::Tile(TextureManager * textureManager, char* fileName, Vector2D textureVertices[])
{
	this->textureManager = textureManager;
	this->fileName = fileName;
	memcpy(this->textureVertices, textureVertices, sizeof(Vector2D)*4);
	
	if(textureManager)
	{
		if(!textureManager->LoadTexture(fileName))
		{
			printf("Failed to load %s\n", fileName);
		}
		else
		{
			textureIndex = textureManager->TextureIndex(fileName);
		}
	}
}
Tile::~Tile()
{
	if(fileName)
	{
		delete(fileName);
		fileName= NULL;
	}
}
bool Tile::Draw(int rotation, Vertex * vertices)
{
	if(textureIndex >= 0)
	{
		if(textureManager)
		{
			textureManager->EnableTexture(textureIndex);
		}
		glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
		glAlphaFunc( GL_GREATER, 0.01 );
	  	glEnable( GL_ALPHA_TEST );
	  	glEnable(GL_TEXTURE_2D);
	  	glColor3f(1,1,1);
	  	glBegin(GL_QUADS);
	  	for(int i=0; i < 4; i++)
	  	{
	  		glTexCoord2f(textureVertices[(i+rotation)%4].x,textureVertices[(i+rotation)%4].y);
	  		glVertex2f(vertices[i].GetPosition().x, vertices[i].GetPosition().y);
	  	}
	  	glEnd();
	  	return true;
	}	
	return false;
}
char * Tile::GetTextureName()
{
	return fileName;
}
Vector2D * Tile::GetTextureVertices()
{
	return textureVertices;
}
